/**
 * 
 */
package info.niwota.fwrite;

import info.niwota.fwrite.imglist.BackgroundImages;

import java.io.File;
import java.io.InputStream;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.net.Uri;
import android.provider.MediaStore.Images;
import android.provider.MediaStore.Images.ImageColumns;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;

/**
 * @author qiangli
 * 
 */
public final class Utils {

	private static final String TAG = "Utils";

	private Utils() {

	}

//	public static void viewAll(Context ctx) {
//
//		final File dir = SDCard.getNoteDir();
//		final String mimetype = "vnd.android.cursor.dir/image";
//		final String bid = getBucketId(dir.getPath());
//		final Uri wsuri = Uri.parse(dir.toURI().toString()).buildUpon()
//				.appendQueryParameter("bucketId", bid).build();
//		viewImage(ctx, wsuri, mimetype);
//
//	}

	public static Uri addImage(ContentResolver cr, File file, String title) {
		return addImage(cr, file, title, System.currentTimeMillis(), null);
	}

	public static Uri addImage(ContentResolver cr, File file, String title,
			long dateTaken, Location location) {
		//
		ContentValues values = new ContentValues(8);
		values.put(Images.Media.TITLE, title);
		values.put(Images.Media.DISPLAY_NAME, file.getName());
		values.put(Images.Media.DATE_TAKEN, dateTaken);
		values.put(Images.Media.MIME_TYPE, "image/jpeg");
		values.put(Images.Media.ORIENTATION, 0);
		values.put(Images.Media.DATA, file.getPath());
		if (location != null) {
			values.put(Images.Media.LATITUDE, location.getLatitude());
			values.put(Images.Media.LONGITUDE, location.getLongitude());
		}
		return cr.insert(STORAGE_URI, values);
	}

	private static final Uri STORAGE_URI = Images.Media.EXTERNAL_CONTENT_URI;

	public static String createName() {
		long date = System.currentTimeMillis();
		return DateFormat.format("yyyy-MM-dd_kkmmss", date).toString();
	}

	public static String createName(String prefix, String ext) {
		long date = System.currentTimeMillis();
		return prefix + DateFormat.format("yyyy-MM-dd_kkmmss", date) + ext;
	}

	public static File findUniqueFile(File file) {
		if (!file.exists()) {
			return file;
		}
		String dir = file.getParent();
		String name = file.getName();
		String ext = "";
		//
		int idx = name.lastIndexOf(".");
		if (idx > 0) {
			ext = name.substring(idx); // including dot
			name = name.substring(0, idx);
		}
		// Try until we find a filename which
		// does not exist yet.
		for (int i = 0; i < Integer.MAX_VALUE; i++) {
			File candidate = new File(dir, name + "-" + i + ext);
			boolean exists = candidate.exists();
			if (!exists) {
				return candidate;
			}
		}
		return null;
	}

	public static File getOutputFile() {
//		if (!SDCard.checkSDCard()) {
//			return null;
//		}
		//
		String name = Utils.createName(); // date
		//
		File dir = SDCard.getNoteDir();
		File f = new File(dir, name + ".jpg");
		File uf = Utils.findUniqueFile(f);
		if (Debug.DEBUG) {
			Log.d(TAG, "getOutputFile: " + uf);
		}
		return uf;
	}

	/**
	 * This is copied from ImageManager and may break
	 * 
	 * @param path
	 * @return
	 */
//	public static String getBucketId(String path) {
//		return String.valueOf(path.toLowerCase().hashCode());
//	}

//	private static void viewImage(Context ctx, Uri uri, String mimetype) {
//		try {
//			final String title = ctx.getString(R.string.text_all_notes);
//			Intent i = new Intent(Intent.ACTION_VIEW);
//			i.setDataAndType(uri, mimetype);
//			i.putExtra("windowTitle", title);
//			// i.putExtra("mediaTypes", "");
//			Intent si = Intent.createChooser(i, title);
//			ctx.startActivity(si);
//		} catch (ActivityNotFoundException e) {
//			if (Debug.DEBUG) {
//				e.printStackTrace();
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//	}

	public static String getDataPath(Context ctx, Uri uri) {
		if (uri.getScheme().equals("file")) {
			return uri.getPath();
		} else {
			Cursor c = ctx.getContentResolver().query(uri,
					new String[] { ImageColumns.DATA }, null, null, null);
			c.moveToFirst();
			String p = c.getString(0);
			c.close();
			return p;
		}
	}
	
	public static Drawable loadImage(Context ctx, Uri uri) {
		File f = new File(getDataPath(ctx, uri));
		return BackgroundImages.loadImage(ctx, f);
	}
	
	public static Drawable loadImage(Context ctx, String uri) {
		Uri u = Uri.parse(uri);
		File f = new File(getDataPath(ctx, u));
		return BackgroundImages.loadImage(ctx, f);
	}

	public static Intent toShareIntent(String subject, String body, Uri uri) {
		Intent i = new Intent();
		i.setAction(Intent.ACTION_SEND);
		String type = "image/*";
		i.setType(type);
		//
		// i.setType("message/rfc822"); //only show email
		// i.setType("text/plain"); //emulator
		// i.setType("message/rfc822"); //phone
		//
		// String subject = getString(R.string.msg_subject_default);
		// String body = getString(R.string.msg_body_default);
		// String subject = Preferences.getSubject(this);
		// String body = Preferences.getBody(this);
		//
		i.putExtra(Intent.EXTRA_SUBJECT, subject);
		i.putExtra(Intent.EXTRA_TEXT, body);
		//
		i.putExtra(Intent.EXTRA_STREAM, uri);
		//
		// mms
		// String phone = Preferences.getPhoneNumber(this);
		// if (phone != null) {
		// i.putExtra("address", phone);
		// }
		i.putExtra("exit_on_sent", true);
		i.putExtra("sms_body", body);
		//
		// etalk
		// i.putExtra(EtalkIntent.EXTRA_NAME, name);
		i.putExtra("instant.mail.extra.uri", uri.getPath());
		i.putExtra("instant.mail.extra.subject", subject);

		return i;
	}

	public static Bitmap loadImage(String pkgpath, String icon) {
		// /info/niwota/fwrite/icon.png
		InputStream is = null;
		try {
			is = Utils.class.getResourceAsStream(pkgpath + icon);
			return BitmapFactory.decodeStream(is);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}

	//	
	// public static void thumbnail(InputStream in, OutputStream out, int width,
	// int height) {
	// Bitmap image = BitmapFactory.decodeStream(in);
	// int w = image.getWidth();
	// int h = image.getHeight();
	// float scalew = ((float) width) / w;
	// float scaleh = ((float) height) / h;
	// float scale = Math.min(scalew, scaleh);
	// Matrix matrix = new Matrix();
	// matrix.postScale(scale, scale);
	// Bitmap resized = Bitmap.createBitmap(image, 0, 0, w, h, matrix, true);
	// resized.compress(Bitmap.CompressFormat.JPEG, 50, out);
	// return;
	// }

	public static Bitmap loadImage(Resources res, int id, int width, int height) {
		Options opt = new Options();
		opt.inJustDecodeBounds = true;
		BitmapFactory.decodeResource(res, id, opt);
		int w = opt.outWidth;
		int h = opt.outHeight;
		//
		float scalew = w / width;
		float scaleh = h / height;
		int scale = (int) Math.max(scalew, scaleh);
		//
		opt.inJustDecodeBounds = false;
		opt.inSampleSize = scale;
		Bitmap bm = BitmapFactory.decodeResource(res, id, opt);
		return bm;
	}

	public static int[] getScreenSize(Context ctx) {
		// 320x240
		WindowManager wm = (WindowManager) ctx
				.getSystemService(Context.WINDOW_SERVICE);
		Display d = wm.getDefaultDisplay();
		final int width = d.getWidth();
		final int height = d.getHeight();
		return new int[] { width, height };
	}

	public static Bitmap loadImage(String file, int width, int height) {
		Options opt = new Options();
		opt.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(file, opt);
		int w = opt.outWidth;
		int h = opt.outHeight;
		//
		float scalew = w / width;
		float scaleh = h / height;
		int scale = (int) Math.max(scalew, scaleh);
		//
		opt.inJustDecodeBounds = false;
		opt.inSampleSize = scale;
		Bitmap bm = BitmapFactory.decodeFile(file, opt);
		return bm;
	}

	public static Bitmap makeTemplate(Context ctx) {
		int[] dim = getScreenSize(ctx);
		int width = dim[0];
		int height = dim[1];
		//
//		Bitmap image = BitmapFactory.decodeResource(ctx.getResources(), res);
//		
//		int w = image.getWidth();
//		int h = image.getHeight();
//		float scalew = ((float) width) / w;
//		float scaleh = ((float) height) / h;
//		float scale = Math.min(scalew, scaleh);
//		scale = (scale > 1.0f ? 1.0f : scale); //
//		Matrix matrix = new Matrix();
//		matrix.postScale(scale, scale);
//		
		//
		final Bitmap.Config c = Bitmap.Config.ARGB_8888;
		
		final Bitmap page = Bitmap.createBitmap(width, height, c);
		final Canvas canvas = new Canvas(page);
		canvas.drawColor(Color.BLACK);
		canvas.setDrawFilter(new PaintFlagsDrawFilter(Paint.DITHER_FLAG, 0));
		
		//canvas.drawBitmap(image, matrix, null);
		
		return page;
	}

	/**
	 * file.toURI().toString() does not work in certain cases (gmail)
	 * 
	 * @param file
	 * @return  file://+path
	 */
	public static Uri toUri(File file) {
		String path = "file://"+file.getAbsolutePath(); 
		Uri uri = Uri.parse(path);
		return uri;
	}
}
